import axios from 'axios';
import store from '../vuex/store'
import router from '../routes'
import Vue from 'vue'
let base = 'http://localhost:57139/api';

export const requestLogin = params => { return axios.post(`${base}/login/LoginAsync`, params).then(res => res.data) };



//用户
export const getUserListPage = params => { return axios.post(`${base}/UserInfo/GetUserPageDataAsync`, params, { indices: false }).then(res => res.data) };
export const loadUserInfo = params => {
    return axios.post(`${base}/UserInfo/LoadUserInfoAsync`, params).then(res => res.data);
};
export const deleteUser = params => {
    return axios.get(`${base}/UserInfo/SoftDeleteUserAsync`, { params: params }).then(res => res.data);
};

export const addOrUpdateUserInfoAsync = params => { return axios.post(`${base}/UserInfo/AddOrUpdateUserInfoAsync`, params).then(res => res.data) };
export const refreshToken = params => {
    return axios.post(`${base}/login/RefreshToken`, params).then(res => res.data)
};

//


//角色
export const getRoleListPage = params => { return axios.post(`${base}/Role/GetRolePageDataAsync`, params, { indices: false }) };
export const addOrUpdateRoleAsync = params => { return axios.post(`${base}/Role/AddOrUpdateRoleAsync`, params).then(res => res.data) };
export const loadRoleFormData = params => {
    return axios.post(`${base}/Role/LoadRoleAsync`, params).then(res => res.data);
};
export const deleteRole = params => {
    return axios.get(`${base}/Role/SoftDeleteRoleAsync`, { params: params }).then(res => res.data);
};
export const roleSelectList = params => {
    return axios.get(`${base}/Role/GetRoleSelectListItem`, { params: params }).then(res => res.data);
};

//权限
export const getPermissionList = params => { return axios.post(`${base}/Permission/GetPermissionListAsync`, params, { indices: false }).then(res => res.data) };
export const getPermissionTypeListItem = params => { return axios.get(`${base}/Permission/GetPermissionTypeListItem`, params, { indices: false }).then(res => res.data) };
export const getPermissionCascaderList = params => { return axios.get(`${base}/Permission/GetPermissionTreeCascaderItemAsync`, params, { indices: false }).then(res => res.data) };
export const addOrUpdatePermissionAsync = params => { return axios.post(`${base}/Permission/AddOrUpdatePermissionAsync`, params).then(res => res.data) };
export const loadPermissionFormData = params => {
    return axios.post(`${base}/Permission/LoadPermissionFormAsync`, params).then(res => res.data);
};
export const deletePermission = params => {
    return axios.get(`${base}/Permission/SoftDeletePermissionAsync`, { params: params }).then(res => res.data);
};

//公用
//得到权限按钮
export const getPermissionButton = params => { return axios.get(`${base}/Permission/GetButtonByParentNameAsync`, { params: params }).then(res => res.data) };
//得到菜单
export const getMenus = params => { return axios.post(`${base}/Permission/GetAllMenusAsync`, params).then(res => res.data) };
export const getMenuss = params => { return axios.post(`${base}/Permission/GetAllMenusAsync`, params).then(res => res.data) };

//模块
export const getModuleListPage = params => { return axios.post(`${base}/Module/GetModulePageDataAsync`, params, { indices: false }) };
export const addOrUpdateModuleAsync = params => { return axios.post(`${base}/Module/AddOrUpdateModuleAsync`, params).then(res => res.data) };
export const deleteModule = params => {
    return axios.get(`${base}/Module/SoftDeleteModuleAsync`, { params: params }).then(res => res.data);
};
export const getModuleListItem = params => {
    return axios.get(`${base}/Module/GetAllModuleToSelectListItemAsync`, { params: params }).then(res => res.data);
};

//审计
export const getAuditListPage = params => { return axios.post(`${base}/Audit/GetAuditPageDataAsync`, params, { indices: false }).then(res => res.data) };

///实体审计
export const getAuditEntryListPage = params => { return axios.post(`${base}/AuditEntry/GetAuditEntryPageDataAsync`, params, { indices: false }).then(res => res.data) };
var storeTemp = store.state;

// 请求延时
axios.defaults.timeout = 10000;
// 添加请求拦截器
axios.interceptors.request.use(function(config) {

    if (storeTemp.token) {
        config.headers.Authorization = `Bearer ${storeTemp.token}`;
    }
    // if (storeTemp.token && (curTime < expiretime && storeTemp.tokenExpiresTime)) {

    //     config.headers.Authorization = `Bearer ${storeTemp.token}`
    // }
    // if (storeTemp.token && storeTemp.tokenExpiresTime) {

    //     config.headers.Authorization = `Bearer ${storeTemp.token}`
    // }
    // saveRefreshtime();
    // 在发送请求之前做些什么
    return config;
}, function(error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});


// 添加响应拦截器
axios.interceptors.response.use(function(response) {

    if (response.status == 200) {
        if (response.data) {
            let data = response.data;

            if (data.type) {

                if (data.type === 1005) {
                    ToLogin();
                } else if (data.type === 1010) {
                    console.log("1010");

                    ToLogin();
                } else if (data.type === 1000) {

                    // router.replace({
                    //     path: "/"
                    // });

                }
            }

        }

    }
    // 对响应数据做点什么
    return response;
}, function(error) {
    if (error.response) {

        if (error.response.status == 401) {


        } else {
            ToLogin();
        }
    }
    if (!error) {

        if (error.response.status == 403) {
            Vue.prototype.$message({
                message: '失败！',
                type: 'error'
            });
            return null;
        }
    }

    return '';
});

const ToLogin = params => {
    store.commit("saveToken", "");
    // store.commit("savetokenExpiresTime", "");
    store.commit("saveTagsData", "");
    window.sessionStorage.removeItem('User');
    router.replace({
        path: "/login"
    });
    window.location.reload();
};
export const saveRefreshtime = params => {

    // this.$store.commit("saveTagsData", JSON.stringify(this.tagsList));
    let refreshTime = window.localStorage.TokenRefreshTime;
    let tokenExpiresTime = window.localStorage.TokenExpiresTime;
    let nowtime = new Date();
    let lastRefreshtime = refreshTime ? new Date(refreshTime) : new Date(-1);
    let expiretime = new Date(Date.parse(tokenExpiresTime))

    let refreshCount = 1; //滑动系数
    if (lastRefreshtime >= nowtime) {
        lastRefreshtime = nowtime > expiretime ? nowtime : expiretime;
        lastRefreshtime.setMinutes(lastRefreshtime.getMinutes() + refreshCount);
        store.commit("saveRefreshTime", lastRefreshtime);

    } else {
        store.commit("saveRefreshTime", new Date(-1));
    }
};